package com.corticon.dialogs.util;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.corticon.dialogs.dao.UserDAO;
import com.corticon.dialogs.dao.UserGroupDAO;
import com.corticon.dialogs.model.BasicQuestionAvailabilityType;
import com.corticon.dialogs.model.BasicQuestionStatusType;
import com.corticon.dialogs.model.PermissionType;
import com.corticon.dialogs.model.QuestionAvailable;
import com.corticon.dialogs.model.User;
import com.corticon.dialogs.model.UserGroup;
import com.corticon.dialogs.util.security.CustomUserDetails;
import com.corticon.dialogs.util.security.SecurityUtils;

/**
 *
 * @author Lifan Yang
 */
@Component("commonSupport")
public class CommonSupport {

    @Resource
    private UserDAO userDAO;
    @Resource
    private UserGroupDAO userGroupDAO;

    public String checkQuestionAvailability(QuestionAvailable questionAvailable) {

        if (questionAvailable.getStatus().getName().equals(
            BasicQuestionStatusType.retired.toString())) {
            return SystemMessages.ACTION_FAILED_PAGE_RETIRED;
        } else if (BasicQuestionAvailabilityType.locked.toString().equals(questionAvailable.
            getAvailability().getName())) {
            return SystemMessages.ACTION_FAILED_PAGE_LOCKED;
        } else {
            return SystemMessages.ACTION_SUCCESS;
        }
    }

    /**
     * Find the User object according to the UserDetails in the SessionContext.
     * @return
     */
    public User findCurrentUser() {
        CustomUserDetails currentUserDetails = SecurityUtils.getCurrentUser();
        return userDAO.load(currentUserDetails.getUsername());
    }

    public void loadUsersAndGroupsInfoByPermission(CustomUserDetails currentUser,
        HttpServletRequest request) {
        List<String> permissions = currentUser.getPermissions();

        if (permissions.contains(PermissionType.GROUP_ADMIN.value()) || permissions.contains(
            PermissionType.AUTHOR.value()) || permissions.contains(PermissionType.REVIEWER.value())) {
            List<User> users = userDAO.findByGroup(currentUser.getGroupName());
            request.setAttribute("users", users);
        } else if (permissions.contains(PermissionType.SYS_ADMIN.value())) {
            List<User> users = userDAO.findAll();
            request.setAttribute("users", users);
            List<UserGroup> groups = userGroupDAO.findAll();
            request.setAttribute("groups", groups);
        }
    }
}
